// Tests.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "sockets/ClientSocket.h"
#include "tstring.h"
#include <tchar.h>

const TCHAR * HOST_ADDR = _T("127.0.0.1");
const TCHAR * HOST_PORT = _T("10000");
const int CONNECTIONS_NUMBER = 1;
const int REQEST_NUMBER = 1;
const unsigned MIN_REQUEST_LEN = 3;
const unsigned MAX_REQUEST_LEN = 4*1024;
const unsigned MAX_CHAR = 256;

_tstring genRequest( int len ){
	_tstring s;
	s.reserve( len );
	for( int i=0; i<len; i++){
		TCHAR c;
		do {
			c = _T('0') + i % 10;
		} while ( !_istalnum(c) );
		s += c;
	}
	s+= _T("\r\n\r\n");
	return s;
}

const TCHAR * HELLO_WORLD_REPLY = _T("HTTP/1.0 200 OK\r\nContent-Length:84\r\n\r\n");
//< Reply string without http reply body.

DWORD WINAPI testThread( LPVOID pParam ){

	DWORD dwErrNum = 0;
	for( unsigned i=0; i<REQEST_NUMBER; i++ ){
		ClientSocket sock;
		sock.connect( HOST_ADDR, HOST_PORT );
		int len = 0;
		do {
			len = rand();
		} while ( len <= MIN_REQUEST_LEN || len >= MAX_REQUEST_LEN );
		_tstring s = _T("GET / HTTP/1.1");
		_tstring s1;
		sock.writeln( s );
		sock.writeln( "" );
		//TCHAR szBuf[MAX_REQUEST_LEN + 50];
		//_stprintf_s( szBuf, MAX_REQUEST_LEN + 50, _T("Data has been sent to server: %s"), s.c_str() );
		//debug( 5, szBuf );
		_tstring sTemp;
		int iContentLen = 0;
		do {
			sock.readln( sTemp );
			s1 += sTemp + _T("\r\n");
			int iPos = s1.find( "Content-Length:" );
			if ( iPos != _tstring::npos ){
				iContentLen = atoi( s1.substr( iPos + strlen("Content-Length:")).c_str() );
			}
		} while ( !sTemp.empty() );
		char* pszBuf = new char[iContentLen];
		sock.read( pszBuf, iContentLen );
		debug( 2, s1.c_str() );
		debug( 2, pszBuf );
		delete[] pszBuf;
		
	}
	_tprintf( _T("Thread #%d, number of dwErrNum: %d\n"), *((int*)pParam ), dwErrNum );
	return dwErrNum;
}

int iParams[CONNECTIONS_NUMBER];

int _tmain(int argc, _TCHAR* argv[])
{
	DWORD errors = 0;
	HANDLE hThreads[CONNECTIONS_NUMBER];
	for( unsigned i=0; i<CONNECTIONS_NUMBER; i++ ){
		iParams[i] = i;
		DWORD dwThreadId;
		hThreads[i] = CreateThread(
			NULL,
			NULL,
			testThread,
			LPVOID(&iParams[i]),
			0,
			&dwThreadId);
	}

	WaitForMultipleObjects( CONNECTIONS_NUMBER, hThreads, TRUE, INFINITE );
	_tprintf( _T("Total number of errors: %d\n"), errors );
	getchar();
	return 0;
}

